import request from '@/utils/request';
import { setToken } from '@/utils/token-util';
import type { ApiResult } from '@/api';
import md5 from 'js-md5';
import type { LoginParam, CaptchaResult, VerifyParam } from './model';

/**
 * 登录
 */
export async function login(data: LoginParam) {
  console.log('===login===' + JSON.stringify(data));
  const res = await request.post<ApiResult<string>>(
    '/login',
    {},
    {
      params: {
        // 账号
        account: data.account,
        // 密码
        password: md5(data.password),
        //登录用户类型
        userType: data.userType,
        //验证码Key
        verifyKey: data.verifyKey,
        //验证码
        verifyCode: data.verifyCode
      }
    }
  );
  if (res.data.success) {
    setToken(res.data.data, true);
    return res.data.msg;
  }
  return Promise.reject(new Error(res.data.msg));
}

/**
 * 获取验证码
 */
export async function getCaptcha(data: VerifyParam) {
  const res = await request.get<ApiResult<CaptchaResult>>('/verify', {
    params: data
  });
  console.log('==123123==' + JSON.stringify(res));
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.msg));
}
